layui.config({
    base: './js/' //你的扩展模块所在目录
}).use(['jquery','layer','ajaxRequest','form','flow'], function(){
    var form = layui.form;
    var $ = layui.jquery;
    var layer = layui.layer;
    var ajaxRequest = layui.ajaxRequest;
    var flow = layui.flow;


    var category = "";
    var keywords = "";

    $(function () {
        // 获取其它页面跳转过来的参数
        var theRequest = getRequest();
        category = theRequest['category'];

        // 加载文章
        initArticle();
        // 加载分类
        getCategory();
        // 加载排行
        initRanking();
        // 加载推荐
        initRecommended();

        // 分类点击事件
        $("body").off('click','#categoryClick').on("click", "#categoryClick", function () {
            category = $(this).attr('title');
            $("#articleListDom").html("");
            initArticle();
        });
    });

    form.on('submit(searchForm)', function(data){
        keywords =$("#keywords").val();
        /*if(keywords==null || keywords==""){
            layer.msg('请输入要搜索的关键字');
            return false;
        }*/
        search();
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    // 加载文章
    function initArticle() {
        flow.load({
            elem: '#articleListDom' //指定列表容器
            // 放开下面两个注解为手动加载
            // ,isAuto: false
            // ,isLazyimg: true
            ,done: function(page, next){ //到达临界点（默认滚动触发），触发下一页
                var lis = [];
                //以jQuery的Ajax请求为例，请求下一页数据（注意：page是从2开始返回）
                $.ajax({
                    url:baseUrl + "/blog/article/getArticleArticleList",
                    data:{'page':page,'limit':indexLimit,'categoryId':category,'title':keywords},
                    type:"GET",
                    async:true,
                    success:function (res) {
                        var total = res.data.total;
                        var list = res.data.rows;

                        $.each(list,function(index,element){

                            // 置顶和原创显示
                            var zhiding = '';
                            var yuancheng = '';
                            if (element.top == 1) {
                                zhiding = '<span class="article_is_top">置顶</span>&nbsp;'
                            }
                            if (element.original == 1){
                                yuancheng = '<span class="article_is_yc">原创</span>&nbsp;'
                            }

                            // 内容截取
                            var content = deleteHtmlTags(element.content);
                            var len  = content.length > 85 ? 86 : content.length;
                            content = content.substr(0,len);

                            lis.push('<div class="article shadow animated zoomIn">\n' +
                                '\t\t\t\t\t\t\t\t<div class="article-left ">\n' +
                                '\t\t\t\t\t\t\t\t\t<img src="'+element.articleCover+'" alt="'+element.title+'">\n' +
                                '\t\t\t\t\t\t\t\t</div>\n' +
                                '\t\t\t\t\t\t\t\t<div class="article-right">\n' +
                                '\t\t\t\t\t\t\t\t\t<div class="article-title">\n' + zhiding + yuancheng +
                                '\t\t\t\t\t\t\t\t\t\t<a href="'+articleUrl + element.id+'.html?watchNumber='+element.watchNumber+'">'+element.title+'</a>\n' +
                                '\t\t\t\t\t\t\t\t\t</div>\n' +
                                '\t\t\t\t\t\t\t\t\t<div class="article-abstract">\n' +
                                ''+content+'</div>\n' +
                                '\t\t\t\t\t\t\t\t</div>\n' +
                                '\t\t\t\t\t\t\t\t<div class="clear"></div>\n' +
                                '\t\t\t\t\t\t\t\t<div class="article-footer">\n' +
                                '\t\t\t\t\t\t\t\t\t<span><i class="fa fa-clock-o"></i>&nbsp;&nbsp;'+element.createdTime+'</span>\n' +
                                '\t\t\t\t\t\t\t\t\t<span class="article-author"><i class="fa fa-user"></i>&nbsp;&nbsp;\' '+element.author+'</span>\n' +
                                '\t\t\t\t\t\t\t\t\t<span><i class="fa fa-tag"></i>&nbsp;&nbsp;<a href="javascript:void(0);"> '+element.categoryName+'</a></span>\n' +
                                '\t\t\t\t\t\t\t\t\t<span class="article-viewinfo"><i class="fa fa-eye"></i>&nbsp;'+element.watchNumber+'</span>\n' +
                                '\t\t\t\t\t\t\t\t\t<span class="article-viewinfo"><i class="fa fa-commenting"></i>&nbsp;'+element.commentNumber+'</span>\n' +
                                '\t\t\t\t\t\t\t\t</div>\n' +
                                '\t\t\t\t\t\t\t</div>');
                        });

                        next(lis.join(''), page < Math.ceil(total/indexLimit));
                    },
                    error:function (res) {

                    }
                });

            }
        });

    }

    // 加载文章分类
    function getCategory() {
        var res = ajaxRequest.sendGet("/blog/article/getCategory",{},false,false);
        var html = "<a href=\"javascript:void (0);\" id=\"categoryClick\">全部</a>";
        if (res) {
            $.each(res.data,function(index,element){
                html = html + '<a id="categoryClick" title="'+element.id+'" href="javascript:void(0) ">'+element.name+'</a>';
            });
            $(".article-category-title").after(html);
        }
    }

    // 加载排行榜数据
    function initRanking() {
        var res = ajaxRequest.sendGet("/blog/article/getRankingArticleList",{'limit':rankingAndRecom},false,false);
        var html = "";
        if (res) {
            $.each(res.data,function(index,element){

                var classa = "";
                if (index == 0){
                    classa = "layui-bg-red";
                } else if (index == 1) {
                    classa = "layui-bg-orange";
                }else if (index == 2) {
                    classa = "layui-bg-green";
                }

                html = html +
                    "<li>\n" +
                    "<span>\n" +
                    "<i class=\"layui-badge-rim "+classa+"\">"+Number(index+1)+"</i>\n" +
                    "</span> &nbsp;&nbsp;\n" +
                    "<a href=\""+articleUrl + element.id + ".html?watchNumber="+element.watchNumber +"\">"+element.title+"</a>\n" +
                    "</li>";

            });
            $("#ranking").html(html);
        }
    }

    // 加载站长推荐数据
    function initRecommended() {
        var res = ajaxRequest.sendGet("/blog/article/getRecommendedArticleList",{'limit':rankingAndRecom},false,false);
        var html = "";
        if (res) {
            $.each(res.data,function(index,element){
                html = html +"<li>\n" +
                    "<span class=\"article_is_yc\">原创</span> &nbsp;&nbsp;\n" +
                    "<a href=\""+articleUrl + element.id + ".html?watchNumber="+element.watchNumber +"\">"+element.title+"</a>\n" +
                    "</li>";
            });
            $("#recommended").html(html);
        }
    }

    // 搜索
    function search(keywords) {
        // layer.msg(keywords);
        $("#articleListDom").html("");
        initArticle();
    }

});


// 将字符串中的html标签进行替换
function deleteHtmlTags(htmlStr){
    //定义script的正则表达式，去除js可以防止注入
    /*var scriptRegex = /<script[^>]*?>[\\s\\S]*?<\\/script>/gm;
    //定义style的正则表达式，去除style样式，防止css代码过多时只截取到css样式代码
    var styleRegex = /<style[^>]*?>[\\s\\S]*?<\\/style>/gm;*/
    //定义HTML标签的正则表达式，去除标签，只提取文字内容
    // 排除所有html标签
    // var htmlRegex = /<[^>]+>/gm;
    var regx = /<[^>]*>|<\/[^>]*>/gm;
    // 排除除了img、p、span标签以外的所有标签
    // var htmlRegex = "(?!<(img|p|span).*?>)<.*?>";
    // var htmlRegex = "(?!<(img).*?>)<.*?>";
    //定义空格,回车,换行符,制表符
    var spaceRegex = /\\s*|\t|\r|\n/gm;
    // 过滤script标签
    // htmlStr = htmlStr.replace(scriptRegex, "");
    // 过滤style标签
    // htmlStr = htmlStr.replace(styleRegex, "");
    // 过滤html标签
    // htmlStr = htmlStr.replace(htmlRegex, "");
    htmlStr = htmlStr.replace(regx, "");
    // 过滤空格等
    htmlStr = htmlStr.replace(spaceRegex, "");
    // 过滤&nbsp;
    htmlStr = htmlStr.replace("&nbsp;", "");
    // 过滤&nbsp
    htmlStr = htmlStr.replace("&nbsp", "");
    // 返回文本字符串
    htmlStr = htmlStr.trim();
    //去除空格" "
    htmlStr = htmlStr.replaceAll(" ", "");

    return htmlStr;
}

// 其它页面跳转过来时获取传入参数
function getRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}